using System.Collections.Generic;
using System.Linq;
using EPiServer.Core;
using EPiServer.UI;

namespace OpenWaves.ActivityFeed.EPiServer
{
    public class ActivityFeedEPiServerConnector : IActivityFeedEPiServerConnector
    {
        private readonly IActivityFeedService activityFeedService;

        public ActivityFeedEPiServerConnector() : this(ServiceLocator.Resolve<IActivityFeedService>())
        {
        }

        public ActivityFeedEPiServerConnector(IActivityFeedService activityFeedService)
        {
            this.activityFeedService = activityFeedService;
        }

        public virtual void OnPagePublished(PageData page)
        {
            this.activityFeedService.PublishUpdate(
                this.GetUpdateContent(page), 
                page.CreatedBy, 
                this.GetSource(page),
                this.GetTopics(page), 
                false,  //IsPublic
                this.GetUserGroups(page));
        }

        protected virtual string GetSource(PageData page)
        {
            return "EPiServer";
        }

        protected virtual IEnumerable<UserGroup> GetUserGroups(PageData page)
        {
            var groups = new List<UserGroup>();
            groups.AddRange(page.ACL.GetEntries().ForRoles().WithReadAccess().Select(e => UserGroup.FromRole(e.Name)));
            groups.AddRange(page.ACL.GetEntries().ForUsers().WithReadAccess().Select(e => UserGroup.FromUserId(e.Name)));
            return groups;
        }

        protected virtual IEnumerable<Topic> GetTopics(PageData page)
        {
            var topics = new List<Topic>();
            topics.AddRange(page.Category.AsTopics());
            topics.Add(Topic.FromUserId(page.CreatedBy));
            return topics;
        }

        protected virtual UpdateContent GetUpdateContent(PageData page)
        {
            return new Page
                       {
                           Title = page.PageName,
                           Description = page.PageName,
                           ThumbnailUrl = "",
                           Url = page.ExternalLinkUrl()
                       };
        }
    }
}